* Replication
* John Gerring, Carl Henrik Knutsen, Matthew Maguire, Svend-Erik Skaaning, Jan Teorell, and Michael Coppedge. 2021. “Democracy and Human Development: Issues of Conceptualization and Measurement.” Democratization 28(2): 308-332.

* Table C10: Tests of MPI using annual data

* Model 6

* set maxvar
clear
clear matrix
clear mata
set maxvar 20000

* set directory

* load data
use "2021_Democratization_replication_data_posteriors.dta", clear

set matsize 10000

* put democracy index on 0-1 scale
foreach x of varlist mpi_med_stock_10 {
quietly sum `x'
quietly gen `x'_scale = (((`x' - r(min)) * (1 - 0)) / (r(max) - r(min)))
quietly replace `x' = `x'_scale
quietly drop `x'_scale
}
*

* Run baseline model
qui xtreg F.imr_gapminder_ipo_ln mpi_med_stock_10 i.year, fe vce(cluster country_id)
qui outreg2 using Table_2_Model_6.dta, label se bdec(3) noni noobs nor nocon nonot drop(i.year) ctitle(" ") addstat("Years", e(g_max), "Countries", e(N_g), "Observations", e(N), "R-squared", e(r2_w)) dta replace

***Monte Carlo Estimates Using UDS 3202 Draw Posterior Distribution***
*Run the monte carlo

forvalues i = 2(1)901 {

*Print out an iteration number
display `i'

* put democracy index on 0-1 scale
foreach x of varlist mpi_v`i'_stock_10 {
quietly sum `x'
quietly gen `x'_scale = (((`x' - r(min)) * (1 - 0)) / (r(max) - r(min)))
quietly replace `x' = `x'_scale
quietly drop `x'_scale
}
*

*Fit the model, using the ith draw from the UDS posterior
quietly xtreg F.imr_gapminder_ipo_ln mpi_v`i'_stock_10 i.year, fe vce(cluster country_id)
qui outreg2 using Table_2_Model_6.dta, label se bdec(3) noni noobs nor nocon nonot drop(i.year) ctitle("`i'") addstat("Years", e(g_max), "Countries", e(N_g), "Observations", e(N), "R-squared", e(r2_w)) dta append

*Extract the coefficients and variance-covariance matrix
matrix b = e(b)
matrix V = e(V)
local blength = colsof(b)

*Preserve the dataset, take a single multivariate normal draw from the
*posterior distribution of the coefficients, and restore the dataset.
*We use the capture command to catch possible errors in drawnorm
*and drop these iterations gracefully.
preserve 
capture quietly drawnorm b1-b`blength', double n(1) means(b) cov(V) clear
if _rc==0 {
mkmat b1-b`blength', matrix(bsample)
matrix posterior = nullmat(posterior) \ bsample
}
else {
display "Error drawing sample...iteration dropped"
}
restore

*Closes the Monte Carlo Loop
}

*Get posterior ready to work with
svmat posterior

*Calculate means and standard deviations
*tabstat posterior*, stat(mean sd)
keep posterior*
quietly outreg2 using Table_2_Model_6, eqkeep(mean sd) bdec(3) replace sum(log) excel
